<template>
    <div class="statistics-section-item" style="padding: 10px">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
            <el-tab-pane :label="TAB_NAME['jwApplyDetail']" name="jwApplyDetail"></el-tab-pane>
            <el-tab-pane :label="TAB_NAME['jwCheckInLogin']" name="jwCheckInLogin"></el-tab-pane>
            <el-tab-pane :label="TAB_NAME['JwSchedule']" name="JwSchedule"></el-tab-pane>
            <el-tab-pane :label="TAB_NAME['TaskStat']" name="TaskStat"></el-tab-pane>
        </el-tabs>
        <div class="statistics-section-item-body">
            <el-row :gutter="24" class="h-full">
                <el-col :span="17">
                    <VChart ref="parRef" :option="parOptions"/>
                </el-col>
                <el-col :span="7">
                    <ul class="province-today-statistics">
                        <li>
                            <div class="title-header">
                                <el-icon>
                                    <Notebook/>
                                </el-icon>
                                <span class="name">办案数量：</span>
                            </div>
                            <span class="total">{{ statistics.jwApplyDetailCount }}</span>
                        </li>
                        <li>
                            <div class="title-header">
                                <el-icon>
                                    <User/>
                                </el-icon>
                                <span class="name">来访人员数量：</span>
                            </div>
                            <span class="total">{{ statistics.jwCheckInLoginCount }}</span>
                        </li>
                        <li>
                            <div class="title-header">
                                <el-icon>
                                    <Place/>
                                </el-icon>
                                <span class="name">执勤人数：</span>
                            </div>
                            <span class="total">{{ statistics.JwScheduleCount }}</span>
                        </li>
                        <li>
                            <div class="title-header">
                                <el-icon>
                                    <Aim/>
                                </el-icon>
                                <span class="name">履职数量：</span>
                            </div>
                            <span class="total">{{ statistics.TaskStatCount }}</span>
                        </li>
                    </ul>
                </el-col>
            </el-row>
        </div>
    </div>
    <div class="statistics-section-item">
        <div class="back-btn" v-if="isBack">
            <el-button type="primary" :icon="ArrowLeft" circle @click="backHandle"/>
        </div>
        <VChart ref="chartRef" :option="barOptions" @click="handleChartClick"/>
    </div>
</template>

<script setup>
import VChart from "vue-echarts";
import {use} from "echarts";
import {GridComponent, TooltipComponent} from "echarts/components";
import {BarChart} from "echarts/charts";
import {CanvasRenderer} from "echarts/renderers";
import {
    getMapData,
    getPoliceAreaStatus,
    getPolicePerformanceStatus,
    getPoliceSecurityStatus,
    getPoliceServiceStatus
} from "@/api/Dashboard/StatisticsSection.js";
import useUserStore from "@/store/modules/user.js";
import dayjs from "dayjs";
import {ArrowLeft} from "@element-plus/icons-vue";

const userUnit = useUserStore().info.unitId;
const timeStamp = dayjs().format('YYYY-MM-DD')

const TAB_KEYS = {
    JW_APPLY: 'jwApplyDetail',
    JW_CHECK_IN: 'jwCheckInLogin',
    JW_SCHEDULE: 'JwSchedule',
    TASK_STAT_COUNT: 'TaskStat'
};
const TAB_NAME = {
    jwApplyDetail: '办案中心',
    jwCheckInLogin: '检察为民服务中心',
    JwSchedule: '机关安保',
    TaskStat: '履职数量'
};
const isBack = ref(false)

const activeName = ref(TAB_KEYS.JW_APPLY);

// 数值分析
const statistics = ref({
    // 办案数量
    jwApplyDetailCount: 0,
    // 来访人员数量
    jwCheckInLoginCount: 0,
    // 执勤人数
    JwScheduleCount: 0,
    // 履职数量
    TaskStatCount: 0,
});

// 图表
const charts = ref({
    // 办案中心
    jwApplyDetail: [],
    // 检察为民服务中心
    jwCheckInLogin: [],
    // 机关安保
    JwSchedule: [],
    // 履职数量
    TaskStat: [],
});

use([
    TooltipComponent,
    GridComponent,
    BarChart,
    CanvasRenderer
]);

const parOptions = ref({
    tooltip: {
        trigger: 'item',
        formatter: '{b} : {c} ({d}%)'
    },
    legend: {
        type: 'scroll',
        orient: 'vertical',
        left: 10,
        top: 20,
        bottom: 20,
    },
    series: {
        name: '区域',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['70%', '50%'],
        data: [],
        itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
        },
        // label: {
        //     show: false
        // },
        emphasis: {
            itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
        }
    }
})

const barOptions = ref({
    title: {
        text: '办案中心使用状态图',
        left: 'right',
        top: 0,
        right: '10px',
        bottom: 0
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross',
            crossStyle: {
                color: '#999'
            }
        }
    },
    grid: {
        left: 10,
        right: 10,
        top: 50,
        bottom: 10,
        containLabel: true
    },
    xAxis: {
        type: 'category',
        data: [],
        axisPointer: {
            type: 'shadow'
        },
        axisLabel: {interval: 0, rotate: 30}
    },
    yAxis: {
        type: 'value'
    },
    series: {
        name: '办案中心',
        type: 'bar',
        // tooltip: {
        //     valueFormatter: function (value) {
        //         return value + ' ml';
        //     }
        // },
        itemStyle: {
            color: 'rgba(37, 232, 11, 1)'
        },
        data: []
    }
});

const getData = async () => {
    const res = await getMapData();
    const keys = [
        // 办案数量
        'jwApplyDetailCount',
        // 来访人员数量
        'jwCheckInLoginCount',
        // 执勤人数
        'JwScheduleCount',
        // 履职数量
        'TaskStatCount'
    ];
    keys.forEach(key => {
        statistics.value[key] = res.data.reduce((total, item) => total + item[key], 0);
    });

    Object.keys(charts.value).forEach(chartKey => {
        charts.value[chartKey] = res.data.map(item => ({
            name: item.depName,
            value: item[`${chartKey}Count`]
        }));
    });

}

const changeChartDataByTabs = async (data) => {
    await fetchChartData(activeName.value, data);
}

onMounted(() => {
    getData().then(res => {
        setOneChartData()
        changeChartDataByTabs({
            unitId: userUnit,
            endYear: timeStamp,
            isUnit: true
        })
    });
});

// 设置第一个饼图
const setOneChartData = () => {
    parOptions.value.series.data = charts.value[activeName.value]
}

// 设置第二个饼图
const setTwoChartData = (xAxisData, seriesData) => {
    barOptions.value.title.text = `${TAB_NAME[activeName.value]}状态图`
    barOptions.value.series.name = `${TAB_NAME[activeName.value]}`
    barOptions.value.xAxis.data = xAxisData;
    barOptions.value.series.data = seriesData;
}

// tabs 切换
const handleClick = (pane) => {
    activeName.value = pane
    setOneChartData()
    //
    // let data = {}
    // if (pane === 'JwSchedule') {
    //     data = {
    //         unitId: userUnit,
    //         startdate: timeStamp
    //     }
    // } else {
    const data = {
        unitId: userUnit,
        endYear: timeStamp,
        isUnit: true
    }
    // }
    changeChartDataByTabs(data)
}
const barListData = ref([]);

// 获取树状图图表数据
const fetchChartData = async (key, data) => {
    const apiMap = {
        // getPoliceCenterBarData
        [TAB_KEYS.JW_APPLY]: getPoliceAreaStatus,
        // 获取检察为名服务的状态图
        [TAB_KEYS.JW_CHECK_IN]: getPoliceServiceStatus,
        // 获取机关安保的状态图
        [TAB_KEYS.JW_SCHEDULE]: getPoliceSecurityStatus,
        // 获取履职数量的状态图
        [TAB_KEYS.TASK_STAT_COUNT]: getPolicePerformanceStatus
    };

    const res = await apiMap[key](data);
    formatBarData(res.data);
};

const oldBarListData = ref([])
// 优化处理树状图
const formatBarData = (data) => {
    if (!isBack.value) {
        oldBarListData.value = JSON.parse(JSON.stringify(data));
    }
    barListData.value = data;
    const xAxisData = data.map(department => department.deptName);
    const seriesData = data.map(department => department.counts);
    setTwoChartData(xAxisData, seriesData)
}

// 第二个树状图返回事件
const backHandle = () => {
    isBack.value = false
    const xAxisData = oldBarListData.value.map(department => department.deptName);
    const seriesData = oldBarListData.value.map(department => department.counts);
    setTwoChartData(xAxisData, seriesData)
}

const clickCount = ref(0)
const handleChartClick = (events) => {
    // console.log(events)
    if (events.type === 'click' && events.componentType === 'series') {
        const selectedDept = barListData.value.find(item => item.deptName === events.name);
        if (!selectedDept || clickCount.value === 1) {
            clickCount.value = 0
            return;
        }

        isBack.value = true;
        // const data = activeName.value === TAB_KEYS.JW_SCHEDULE
        //     ? {unitId: selectedDept.deptId, startdate: timeStamp}
        //     : {unitId: selectedDept.deptId, endDate: timeStamp, isUnit: true};
        const data = {
            unitId: selectedDept.deptId,
            endYear: timeStamp,
            isUnit: true
        };

        changeChartDataByTabs(data);

        clickCount.value += 1
        console.log(barListData.value.filter(item => item.deptName === events.name)[0]['deptId'])
        // alert(`你点击了${events.seriesName}的数据项，值为：${events.value} ml`);
    }
};
</script>

<style scoped lang="scss">
:deep(.el-card) {
    width: 100%;
    height: 100%;
}

.tabs-btn {
    position: relative;

}

.statistics-section-item-body {
    position: relative;
    overflow: hidden;
    height: calc(100% - 54px);

}

.province-today-statistics {
    position: relative;
    overflow: visible;
    margin: 0;
    padding: 0;

    li {
        display: flex;
        list-style: none;
        border-bottom: 1px dashed #DBDFE9;
        justify-content: space-between;
        align-items: center;
        padding-top: 0.5rem;
        padding-bottom: 0.5rem;
        font-size: 14px;
        line-height: 22px;
        color: var(--el-text-color-primary);

        .title-header {
            display: flex;
            align-items: center;

            :deep(.el-icon) {
                margin-right: 5px;
            }
        }

        .total {
            font-weight: bolder;
        }

        &:last-child {
            border-bottom: none;
        }
    }
}

.back-btn {
    position: absolute;
    left: 5px;
    top: 3px;
    z-index: 9;
}
</style>